<template>
  <div style="width: 1000px; margin: 0 auto">
    <h1>登录页面</h1>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="手机号" prop="userMobile">
        <el-input v-model="ruleForm.userMobile" />
      </el-form-item>
      <el-form-item label="密码" prop="userPass">
        <el-input v-model="ruleForm.userPass" show-password />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { login } from "../api/api";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
interface RuleForm {
  name: string;
  region: string;
  count: string;
  date1: string;
  date2: string;
  delivery: boolean;
  location: string;
  type: string[];
  resource: string;
  desc: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  userMobile: "",
  userPass: "",
});

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules>({
  userMobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  userPass: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{3,10}$/,
      message: "密码必须由大小写字母，数字组成，长度必须在3-10位",
      trigger: "blur",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      login(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("登录成功");
          window.sessionStorage.setItem("user", JSON.stringify(res.data.data));
          window.sessionStorage.setItem("token", res.data.data.token);
          router.push("/home");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>
